package com.hxzy.controller.unit;

import com.alibaba.fastjson.JSONObject;
import com.hxzy.util.BeanValidatorUtil;
import com.hxzy.common.BaseServlet;
import com.hxzy.common.ResultAjax;
import com.hxzy.entity.Unit;
import com.hxzy.service.UnitService;
import com.hxzy.service.impl.UnitServiceImpl;
import com.hxzy.util.SnowFlakeUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Set;
import java.util.UUID;

/**
 * @Author: lqq
 * @Description:
 * @Date: 2022/3/8 16:28
 */
@WebServlet(urlPatterns = "/unit/addJson")
public class AddUnitJson extends BaseServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        try {
            Unit unit = super.CollectiongParameterToJSON(req, Unit.class);
            SnowFlakeUtil snowFlakeUtil=new SnowFlakeUtil(0,0);
            Long l = snowFlakeUtil.nextId();
            unit.setId(l.toString());
            Set<String> validator = BeanValidatorUtil.validator(Unit.class, unit);
            if (validator.isEmpty()){
                UnitService service=new UnitServiceImpl();
                int insert = service.insert(unit);
                ResultAjax resultAjax=null;
                if (insert>0){
                    resultAjax=ResultAjax.success("加入成功");
                }else {
                    resultAjax= ResultAjax.error("加入失败");
                }
                super.render(resp, JSONObject.toJSONString(resultAjax));
            }else {
                
                String next = validator.iterator().next();
                ResultAjax resultAjax = ResultAjax.error(next);
                super.render(resp, JSONObject.toJSONString(resultAjax));
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }
}
